<?php
/**
 * 所属项目 商业版.
 * 开发者: 陈一枭
 * 创建日期: 8/7/14
 * 创建时间: 9:52 AM
 * 版权所有 想天软件工作室(www.ourstu.com)
 */

namespace Appstore\Model;


use Think\Model;

class AppstoreGoodsModel extends Model
{
    protected $entity = 'Plugin'; //1插件2模块3主题4服务

    /**
     * @param $data
     * @return array
     * @auth 陈一枭
     */
    public function combineData($data)
    {
        $data['user'] = query_user(array('nickname', 'space_url'), $data['uid']);
        $shop = D('AppstoreShop')->find($data['uid']);
        if ($shop['status'] == 1) {
            $data['shop'] = $shop;
        }
        $resource = D('AppstoreResource')->find($data['id']);
        $ext = D('Appstore' . $this->entity)->find($data['id']);

        if ($resource)
            $data = array_merge($data, $resource);
        if ($ext)
            $data = array_merge($data, $ext);

        $versions = D('AppstoreVersion')->where(array('status' => 1, 'goods_id' => $data['id']))->order('update_time desc')->limit(5)->select();
        $data['versions'] = $versions;
        $data['user'] = query_user(array('avatar128', 'nickname', 'space_url', 'space_link', 'rank_link'), $data['uid']);
        $data['developer'] = M('AppstoreDeveloper')->find($data['uid']);
        return $data;
    }

    public function getLimit($map = array(), $limit = 10, $order = 'update_time desc', $field = '*')
    {
        $data = D('AppstoreGoods')->field($field)->where($map)->order($order)->limit($limit)->select();
        foreach ($data as &$v) {
            $this->entity = $v['entity'];
            $v = $this->combineData($v);
        }
        return $data;
    }

    public function getById($id)
    {
        $goods = $this->where(array('id' => $id))->find();
        $this->entity = $goods['entity'];
        $goods = $this->combineData($goods);
        return $goods;
    }

    /**
     * 获取商品列表
     * @param $map
     * @return mixed
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getGoodsList($map)
    {
        $list = $this->where($map)->select();
        return $list;
    }

    /**
     * @param array $map
     * @param int $limit
     * @param string $order
     * @param int $more
     * @param string $field
     * @return mixed
     * @author 郑钟良<zzl@ourstu.com>
     */
    public function getListPage($map = array(), $limit = 10, $order = 'id desc', $more = 0, $field = '*')
    {
        $goods = D('AppstoreGoods')->field($field)->where($map)->order($order)->findPage($limit);

        if ($more) {
            foreach ($goods['data'] as &$v) {
                $v = $this->combineData($v);
            }
            unset($v);
        }
        return $goods;
    }


    public function checkGoodsIsBuy($goods_id, $uid = 0)
    {
        if (check_auth('Appstore/Admin/manage')) {
            return true;
        }

        $count = M('appstore_price_max')->where(array('uid' => $uid, 'goods_id' => $goods_id))->count();
        return $count;
    }
} 